<template>
	<fui-button @click="auth">
		授权
	</fui-button>
</template>

<script>
	import {
		defineComponent
	} from "vue"
	import {
		AuthApi
	} from "../../api/login";
	import {
		MainPages
	} from "../../config/router-config";

	import {
		queryParams
	} from "../../utils/util";
	import {
		isWechat
	} from "../../utils/wechat";
	import {
		mapActions
	} from 'pinia'
	import {
		useAuthStore
	} from "../../store/modules/auth";
	import _ from 'lodash'
	import {
		WX_APPID
	} from "../../_env";
	export default defineComponent({
		data() {
			return {

			}
		},
		onLoad(options) {
			if (isWechat()) {
				let code = this.getUrlCode('code')

				console.log(code, 'ddd');
				if (code) {

					this.login(code)
				}
			}
			console.log(options, 'options');
		},

		methods: {
			...mapActions(useAuthStore, ['setAuthInfo', 'setToken']),
			getUrlCode(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location
					.href) || [, ''])[1].replace(/\+/g, '%20')) || null
			},

			async login(code) {
				try {
					const res = await AuthApi.getOpenId(code)
					this.setAuthInfo(res.data)
					console.log(res);

					const l = await AuthApi.login({
						openid: res.data.openid
					})
					if (l.code === 401) {
						uni.showModal({
							title: '提示',
							content: '账户未绑定,跳转至注册页面',
							showCancel: false,
							success() {
								uni.navigateTo({
									url: `${MainPages.LOGIN.router}?openId=${code}`
								})
							}
						})

					} else {
						console.log('ddddddddddddddd');
						this.setToken(l.data)
						uni.showToast({
							icon: 'success',
							title: '登录成功',
						})
						_.delay(() => {
							uni.hideToast()
							uni.navigateTo({
								url: `${MainPages.Index.router}`
							})
						}, 1000)

					}

				} catch (err) {

				}
			},
			auth() {
				if (isWechat()) {
					let local = encodeURIComponent(window.location.href)
					console.log(local, 'sss');
					let appid = WX_APPID;
					const href = `
					https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${local}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
					`
					window.location.href = href
				} else {
					uni.showModal({
						content: '请在微信中打开',
						showCancel: false
					})
				}
			}
		}
	})
</script>

<style>

</style>